<template>
  <el-menu
      :default-active="activeMenuRef"
      class="el-menu-vertical-demo"
      :collapse="isCollapse"
      @open="handleOpen"
      @close="handleClose"
      @select="handleMenuSelect"
      :router="true"
  >
    <!-- 固定菜单 -->
    <el-menu-item index="/dashboard">
      <span v-if="isCollapse==false" style="color: #000;height: 75px;line-height: 75px;font-size: 30px;">XX公司</span>
      <el-icon v-else :style="{ fontSize: 30 + 'px',color:'#000' }">
        <ElemeFilled/>
      </el-icon>
    </el-menu-item>
    <template v-for="item in menuData">
      <!-- 渲染一级菜单 -->
      <el-sub-menu
          v-if="item.children && item.children.length"
          :index="item.path"
          :key="item.path"
      >
        <template #title>
          <el-icon>
            <component :is="item.meta.icon"/>
          </el-icon>
          <span>{{ item.meta.title }}</span>
        </template>
        <!-- 使用 SubMenuComponent 渲染子菜单 -->
        <sub-menu-component :children="item.children"/>
      </el-sub-menu>
      <el-menu-item v-else :index="item.path">
        <el-icon>
          <component :is="item.meta.icon"/>
        </el-icon>
        <template #title>{{ item.meta.title }}</template>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import SubMenuComponent from './SubMenuComponent.vue';
import {MenuItem} from '@/api/menu/model';
import { useRoute } from 'vue-router';
import MenuAPI from "@/api/menu";
// 获取当前路由信息
const route = useRoute();

// 定义接收的属性
const props = defineProps({
  isCollapse: Boolean,
  activeMenu: String,
});
const activeMenuRef = ref(props.activeMenu); // 本地活动菜单
// 监听 props.activeMenu 的变化
watch(
    () => props.activeMenu,
    (newVal) => {
      console.log("发生变化",newVal)
      activeMenuRef.value = newVal;
    }
);

// 接收父组件事件
const emit = defineEmits(['menu-selected']);

// 选中菜单时触发的函数
const handleMenuSelect = (key: string) => {
  activeMenuRef.value = key;
  const selected = getAllChildren(menuData.value).findLast((item) => item.path === key);
  if (selected) {
    emit('menu-selected', { name: selected.meta.title, route: selected.path });
  }
};
const handleOpen = (key: string, keyPath: string[]) => {
  console.log("菜单打开事件：", key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log("菜单关闭事件：", key, keyPath)
}

// 初始化菜单数据
const menuData = ref<MenuItem[]>([]);

// 模拟获取菜单数据
const fetchMenuData = async () => {
  try {
    const res = await MenuAPI.list();
    console.log('菜单数据:', res);
    return res.data; // 假设 API 返回的数据在 `res.data`
  } catch (error) {
    console.error('获取菜单数据失败:', error);
    return []; // 失败时返回一个空数组
  }
};

// 获取菜单数据中的所有 children集合
function getAllChildren(menuList: any[]): any[] {
  let result: any[] = [];
  // 遍历每个菜单项
  menuList.forEach((menu) => {
    result = result.concat(menu);
    // 如果该菜单项有 children，则将其展开并加入到 result 中
    if (menu.children) {
      // 递归地获取子菜单的 children
      result = result.concat(menu.children);
    }
  });
  return result;
}
onMounted(async () => {
  menuData.value = await fetchMenuData();
  activeMenuRef.value = props.activeMenu || menuData.value[0].path; // 初始化菜单
  handleMenuSelect(route.path)
});
</script>

<style scoped>
</style>